package com.cskaoyan.demo7.service;

import com.cskaoyan.demo7.bean.model.*;
import com.cskaoyan.demo7.bean.req.GoodsCreateVo;
import com.cskaoyan.demo7.bean.resp.GoodsDetailVo;
import com.cskaoyan.demo7.mapper.MarketGoodsAttributeMapper;
import com.cskaoyan.demo7.mapper.MarketGoodsMapper;
import com.cskaoyan.demo7.mapper.MarketGoodsProductMapper;
import com.cskaoyan.demo7.mapper.MarketGoodsSpecificationMapper;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description：
 * @Author：BLUEBLANK
 * @Date：2024/4/22 19:51
 */

@Service("goodsService")
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private MarketGoodsMapper goodsMapper;
    @Autowired
    private MarketGoodsAttributeMapper goodsAttributeMapper;
    @Autowired
    private MarketGoodsProductMapper goodsProductMapper;
    @Autowired
    private MarketGoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    private IssueService issueService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private UserService userService;


    @Override
    @Transactional
    public void create(GoodsCreateVo goodsCreateVo) {
        // 1. 插入商品表
        MarketGoods goods = goodsCreateVo.getGoods();
        Date current = new Date();
        goods.setAddTime(current);
        goods.setUpdateTime(current);
        goods.setDeleted(false);
        goodsMapper.insertSelective(goods);

        // 获取商品id
        int goodsId = goods.getId();

        // 异常
        // int i = 1 / 0;

        // 2. 插入商品属性表
        List<MarketGoodsAttribute> attributes = goodsCreateVo.getAttributes();
        attributes.forEach(attribute -> {
            attribute.setGoodsId(goodsId);
            attribute.setAddTime(current);
            attribute.setUpdateTime(current);
            attribute.setDeleted(false);
        });
        goodsAttributeMapper.batchInsert(attributes);
        // 3. 插入商品货品表
        List<MarketGoodsProduct> products = goodsCreateVo.getProducts();
        products.forEach(product -> {
            product.setGoodsId(goodsId);
            product.setAddTime(current);
            product.setUpdateTime(current);
            product.setDeleted(false);
        });
        goodsProductMapper.batchInsert(products);
        // 4. 插入商品规格表
        List<MarketGoodsSpecification> specifications = goodsCreateVo.getSpecifications();
        specifications.forEach(specification -> {
            specification.setGoodsId(goodsId);
            specification.setAddTime(current);
            specification.setUpdateTime(current);
            specification.setDeleted(false);
        });
        goodsSpecificationMapper.batchInsert(specifications);
    }

    @Override
    public GoodsDetailVo detail(Integer id) {
        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();

        // =============1.根据商品id查询商品表================================================
        MarketGoods goods = goodsMapper.selectByPrimaryKey(id);
        goodsDetailVo.setInfo(goods);
        // =============2.根据商品id查询商品属性表==============================================
        MarketGoodsAttributeExample attributeExample = new MarketGoodsAttributeExample();
        attributeExample.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<MarketGoodsAttribute> attributes = goodsAttributeMapper.selectByExample(attributeExample);
        goodsDetailVo.setAttribute(attributes);
        // =============3.specification=======================================================
        MarketGoodsSpecificationExample specificationExample = new MarketGoodsSpecificationExample();
        specificationExample.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<MarketGoodsSpecification> specifications = goodsSpecificationMapper.selectByExample(specificationExample);
        // 根据名称聚合
        Map<String, List<MarketGoodsSpecification>> specificationMap = specifications.stream().collect(Collectors.groupingBy(MarketGoodsSpecification::getSpecification));
        // 封装到对应的dto
        ArrayList<GoodsDetailVo.SpecificationListDTO> specificationList = new ArrayList<>();
        specificationMap.entrySet().forEach(entry -> {
            GoodsDetailVo.SpecificationListDTO specificationListDTO = new GoodsDetailVo.SpecificationListDTO();
            specificationListDTO.setName(entry.getKey());
            specificationListDTO.setValueList(entry.getValue());
            specificationList.add(specificationListDTO);
        });
        goodsDetailVo.setSpecificationList(specificationList);

        // =============4.issue=======================================================
        List<MarketIssue> issues = issueService.list();
        goodsDetailVo.setIssue(issues);

        // =============5.userHasCollect================================================
        // 没有登录，没有用户id，默认没有收藏
        goodsDetailVo.setUserHasCollect(0);


        // =============6.comment================================================
        // GoodsDetailVo.CommentDTO commentDTO = commentService.queryByGoodsId(id);
        List<MarketComment> comments = commentService.queryByGoodsId(id);
        GoodsDetailVo.CommentDTO commentDTO = new GoodsDetailVo.CommentDTO();
        commentDTO.setCount(commentService.countByGoodsId(id));
        ArrayList<GoodsDetailVo.CommentDTO.DataDTO> data = new ArrayList<>();
        comments.forEach(comment -> {
            GoodsDetailVo.CommentDTO.DataDTO dataDTO = new GoodsDetailVo.CommentDTO.DataDTO();
            BeanUtils.copyProperties(comment, dataDTO);
            // 补充用户信息
           MarketUser marketUser = userService.queryById(comment.getUserId());
            dataDTO.setNickname(marketUser.getNickname());
            dataDTO.setAvatar(marketUser.getAvatar());
            data.add(dataDTO);
        });
        commentDTO.setData(data);
        goodsDetailVo.setComment(commentDTO);

        // =============7.share================================================
        // 默认false
        goodsDetailVo.setShare(false);

        // =============8.brand================================================
        MarketBrand brand = null;
        if(goods.getBrandId() != null){
            brand = brandService.queryById(goods.getBrandId());
        }
        goodsDetailVo.setBrand(brand);

        // =============9.productList================================================
        MarketGoodsProductExample productExample = new MarketGoodsProductExample();
        productExample.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<MarketGoodsProduct> products = goodsProductMapper.selectByExample(productExample);
        goodsDetailVo.setProductList(products);

        return goodsDetailVo;

    }

    @Override
    public MarketGoods selectByPrimaryKey(Integer goodsId) {
        // 上架状态，不是删除状态
        MarketGoodsExample goodsExample = new MarketGoodsExample();
        goodsExample.createCriteria().andIdEqualTo(goodsId).andIsOnSaleEqualTo(true).andDeletedEqualTo(false);
        List<MarketGoods> marketGoods = goodsMapper.selectByExample(goodsExample);
        return !marketGoods.isEmpty() ? marketGoods.get(0) : null;
    }
}
